// 引入mutation-type
import {
  ADD_GOODS,
  INIT_SHOP_CART,
  REDUCE_GOODS,
  SINGLE_SELECT_GOODS,
  ALL_SELECT_GOODS,
  DELETE_SELECT_GOODS,
  USER_INFO,
  INIT_USER_INFO,
  CHANGE_USER_NICK_NAME,
  USER_INFO_BRITHDAY,
  USER_INFO_SEX,
  LOGIN_OUT,
  INIT_USER_SHOPPING_ADDRESS,
  ADD_USER_SHOPPING_ADDRESS,
  DELETE_USER_SHOPPING_ADDRESS,
  CHANGE_USER_SHOPPING_ADDRESS
} from './mutation-type'
import Cookies from "js-cookie";
// 引入本地存储
import {
  getLocalStore,
  setLocalStore,
  removeLocalStore
} from '../config/global'
import {
  ADD_TO_CART
} from "../config/pubsub_type";
export default {
  [ADD_GOODS](state, {
    goodsID,
    goodsName,
    smallImage,
    goodsPrice
  }) {
  },
  // 添加商品进购物车
  [ADD_TO_CART](state, goods) {
    // 判断是否有用户登录
    // if (state.userInfo.token) {
    // 1.3 添加数据
    // 延迟900毫秒等待动画结束
    setTimeout(() => {
      this.commit('ADD_GOODS', {
        goodsID: goods.id,
        goodsName: goods.name,
        smallImage: goods.small_image,
        goodsPrice: goods.price
      })
      // Toast({
      //   message: '成功加入购物车',
      //   duration: 800
      // })
    }, 900);
    // } else {
    // 1.4 如何没有登录跳转到登录界面
    // router.push('/login');
    // }
  },

  // 7.保存用户信息到本地
  [USER_INFO](state, {
    userInfo
  }) {
    // 7.1 把外界传来的userInfo保存到state中的userInfo
    state.userInfo = userInfo;
    // 7.2 保存到本地缓存中
    setLocalStore('userInfo', state.userInfo);
  },
  //  8.初始化获取用户信息
  [INIT_USER_INFO](state) {
    // 8.1 先存本地用户数据
    let initUserInfo = getLocalStore('userInfo');
    if (initUserInfo) {
      state.userInfo = JSON.parse(initUserInfo);
    }
  },
  //  16.初始化获取用户收货地址
  [INIT_USER_SHOPPING_ADDRESS](state) {
    let initUsershoppingAddress = getLocalStore('shippingAddress');
    state.shippingAddress = JSON.parse(initUsershoppingAddress) || []
  },
  // 17.增加用户地址
  [ADD_USER_SHOPPING_ADDRESS](state, {
    content
  }) {
    // 17.1 添加用户地址
    state.shippingAddress = [...state.shippingAddress, content];
    // 17.2 将数据存储到本地
    setLocalStore('shippingAddress', state.shippingAddress);
  },
  // 18.删除用户地址
  [DELETE_USER_SHOPPING_ADDRESS](state, {
    id
  }) {
    // 18.1 过滤要删除的地址
    state.shippingAddress = state.shippingAddress.filter(item => item.id !== id)
    // 18.2 更新本地数据
    setLocalStore('shippingAddress', state.shippingAddress);
  },
  // 19.修改用户地址信息
  [CHANGE_USER_SHOPPING_ADDRESS](state, {
    content
  }) {
    // 19.1 找到要被修改地址的索引
    const index = state.shippingAddress.findIndex(item => item.id === content.id)
    state.shippingAddress.splice(index, 1, content)
    // 19.2 更新本地数据
    setLocalStore('shippingAddress', state.shippingAddress);
  },
  // 切换语言
  SET_LANGUAGE: (state, language) => {
    state.language = language;
    Cookies.set("language", language);
  }
}